package com.leilei;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.Arrays;
import java.util.List;

/**
 * @author lei
 * @version 1.0
 * @date 2021/4/10 21:32
 * @desc min 最小数据算子
 */
public class MinOperator {
    public static void main(String[] args) throws Exception {
        List<User> users = Arrays.asList(new User("张三", 12), new User("张三", 18),
                new User("李四", 22), new User("李四", 29), new User("麻子", 35));

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 设置并行度为1 （1个线程执行，以便观察）
        env.setParallelism(1);
        env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
        // 加载数据源
        DataStreamSource<User> stream = env.fromCollection(users);
        // 使用KeyBy算子
        KeyedStream<User, String> keyedStream = stream.keyBy(new KeySelector<User, String>() {
            @Override
            public String getKey(User value) throws Exception {
                return value.name;
            }
        });
        SingleOutputStreamOperator<User> age = keyedStream.sum("age");

        age.print("sum:");
        env.execute();
    }

    @NoArgsConstructor
    @AllArgsConstructor
    @Data
    @Builder
    public static class User {
        private String name;
        private Integer age;
    }

}
